package org.example.springsecurity2.config;

import jakarta.servlet.http.HttpSession;
import org.example.springsecurity2.handler.MyLoginFailureHandler;
import org.example.springsecurity2.handler.MyLoginSuccessHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
        http.authorizeHttpRequests(resp -> {
            resp.requestMatchers("/login.html","/fail.html","/styles.css","/style1.css").permitAll(); // 不需要认证的资源
            resp.requestMatchers("/css/*.css","/js/*.js","/img/**").permitAll(); // 静态资源不需要认证
            resp.anyRequest().authenticated();//其余所有请求都需要认证
        });
        http.formLogin(form-> {
            form.loginPage("/toLogin")
                    .usernameParameter("username")
                    .passwordParameter("password")
                    .loginProcessingUrl("/login")
                    .successHandler(new MyLoginSuccessHandler())
                    .failureHandler(new MyLoginFailureHandler())
                    .permitAll()
            ;
        });
        http.logout(logout ->
        {logout

                        .clearAuthentication(true)
                        .invalidateHttpSession(true)
                .logoutSuccessUrl("/toLogin");}
        );
        http.csrf(
                csrf -> csrf.disable()
        );
        http.rememberMe(
                rememberMe -> rememberMe.key("myAppKey").tokenValiditySeconds(60*60*24*30)


        );
        http.sessionManagement(
                session ->session
                        .invalidSessionUrl("/fail")
                        .maximumSessions(1)
                        .maxSessionsPreventsLogin(true)
        );
        return http.build();
    }
    @Bean
    public WebSecurityCustomizer webSecurityCustomizer(){
        return (web)->web.ignoring().requestMatchers("/js/**","/css/**","/img/**");
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SessionRegistry sessionRegistry(){
        return new SessionRegistryImpl();
    }
}
